//
//  SendFriendViewController.m
//  iOS_beboy
//
//  Created by Chuz NetTech on 17/10/23.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "SendFriendViewController.h"
#import "BDTextView.h"
#import "CameraPhotoBehavior.h"
#import "BDUserModel.h"
#import "NSAttributedString+LiuqsExtension.h"
#import "LiuqsEmoticonKeyBoard.h"

@interface SendFriendViewController ()<LQPhotoPickerViewDelegate,BDTextViewDelegate,UIGestureRecognizerDelegate>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) BDTextView *textView;
//文字个数提示label
@property (nonatomic, strong) UILabel *textNumberLabel;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) UIButton *faceButton;
@property (nonatomic, strong) LiuqsEmoticonKeyBoard *emoticonKeyborad;
@property (nonatomic, strong) NSString *keyboardType;

@end

@implementation SendFriendViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = ASLocalizedString(@"编辑内容");
    self.keyboardType = @"1";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:ASLocalizedString(@"发送")style:UIBarButtonItemStylePlain target:self action:@selector(onClickedOKbtn)];
    self.navigationItem.rightBarButtonItem = rightBarItem;

    self.textView = [[BDTextView alloc]initWithFrame:CGRectMake(10, 0, kBDScreenWidth - 20, 120)];
    [_textView setPlaceHolderFont:[UIFont systemFontOfSize:14]];
    [_textView setPlaceholder:ASLocalizedString(@"说出你此刻想说的话.....")];
    _textView.textViewDelegate = self;
    [self.view addSubview:_textView];
    
    self.textNumberLabel = [[UILabel alloc]init];
    _textNumberLabel.left = 10;
    _textNumberLabel.top = _textView.bottom;
    _textNumberLabel.size = CGSizeMake(kBDScreenWidth - 20, 15);
    _textNumberLabel.textAlignment = NSTextAlignmentRight;
    _textNumberLabel.font = [UIFont boldSystemFontOfSize:12];
    _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    _textNumberLabel.backgroundColor = [UIColor whiteColor];
    _textNumberLabel.text = @"0/250    ";
    [self.view addSubview:_textNumberLabel];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 135, kBDScreenWidth, kBDScreenHeight - 135)];
    [self.view addSubview:_scrollView];
    
    
    //收起键盘
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped)];
    tapGr.cancelsTouchesInView = NO;
    tapGr.delegate = self;
    [self.view addGestureRecognizer:tapGr];
    
    
    
    self.LQPhotoPicker_superView = _scrollView;
    
    self.LQPhotoPicker_imgMaxCount = 9;
    
    [self LQPhotoPicker_initPickerView];
    
    self.LQPhotoPicker_delegate = self;
    
    self.faceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _faceButton.frame = CGRectMake((kBDScreenWidth - 25) / 2, kBDScreenHeight - 25 - 12 - 135 - kBDTopHeight, 25, 25);
    _faceButton.endWindowEditingWhenTouch = NO;
    [_faceButton setImage:[UIImage imageNamed:@"biaoqing2"] forState:UIControlStateNormal];
    [_scrollView addSubview:_faceButton];
    [_faceButton addTarget:self action:@selector(faceButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [[_faceButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        _emoticonKeyborad.hidden = NO;
        [UIView animateWithDuration:0.2 animations:^{
            _emoticonKeyborad.bottom = kBDScreenHeight - 40;
        }];
    }];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    
    self.emoticonKeyborad.hidden = YES;
       
    
}

- (void)viewTapped{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.2 animations:^{
        _emoticonKeyborad.bottom = kBDScreenHeight + _emoticonKeyborad.height;
        
    }];
}

-(void)faceButtonAction{
    _emoticonKeyborad.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        _emoticonKeyborad.bottom = kBDScreenHeight - 40;
    }];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isKindOfClass:[UIButton class]]) {
        [self faceButtonAction];
        [self.view endEditing:YES];
        return NO;
    }
    return YES;
}


- (BOOL)bdTextView:(BDTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    NSString *str = textView.text;
    
    if (str.length > 250)
    {
        NSRange rangeIndex = [str rangeOfComposedCharacterSequenceAtIndex:250];
        
        if (rangeIndex.length == 1)//字数超限
        {
            textView.text = [str substringToIndex:250];
            //这里重新统计下字数，字数超限，我发现就不走textViewDidChange方法了，你若不统计字数，忽略这行
            _textNumberLabel.text = [NSString stringWithFormat:@"%lu/250    ",(unsigned long)textView.text.length];
        }else{
            NSRange rangeRange = [str rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 250)];
            textView.text = [str substringWithRange:rangeRange];
            _textNumberLabel.text = [NSString stringWithFormat:@"%lu/250    ",(unsigned long)textView.text.length];
        }
        return NO;
    }
    
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    
    return YES;
}

- (void)bdTextViewDidChangeSelection:(BDTextView *)textView{
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/250    ",(unsigned long)textView.text.length];
}

-(void)bdTextViewDidChange:(BDTextView *)textView{
    if (textView.text.length > 250)
    {
        textView.text = [textView.text substringToIndex:250];
    }
}

-(void)onClickedOKbtn{
    if ([_textView.attributedText getPlainString].length == 0) {
        [MBManager showBriefAlert:ASLocalizedString(@"文本不能为空") clickHidden:NO clickBlock:nil];
    }else{
    [MBManager showLoadingAlert:ASLocalizedString(@"正在上传") clickHidden:NO clickBlock:nil];
        
    NSString *url = [NSString stringWithFormat:@"%@circles",KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    NSDictionary *dic = @{@"content":[_textView.attributedText getPlainString]};

//    self.imageArray = [NSMutableArray array];
    
//    [self.imageArray addObjectsFromArray:];
//    for (int i = 0; i < [self LQPhotoPicker_getBigImageArray].count; i++) {
//        [self.imageArray addObject:UIImageJPEGRepresentation([self LQPhotoPicker_getBigImageArray][i], 1)];
//    }

    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:dic validation:headValid name:@"images[]" dataArray:[self LQPhotoPicker_getBigImageArray] automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        [MBManager showBriefAlert:ASLocalizedString(@"发表成功")clickHidden:NO clickBlock:nil];
         [[NSNotificationCenter defaultCenter] postNotificationName:@"sendFriend" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
       
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [MBManager showBriefAlert:ASLocalizedString(@"发表失败")clickHidden:NO clickBlock:nil];
    }];
    }
}

-(void)keyboardWillShow:(NSNotification *)objectCation{
    CGRect keyboardFrame = [[[objectCation userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    _faceButton.frame = CGRectMake((kBDScreenWidth - 25) / 2, kBDScreenHeight - 25 - 12 - 135 - kBDTopHeight - keyboardFrame.size.height, 25, 25);
}

-(void)keyboardWillHide:(NSNotification *)objectCation{
    _faceButton.frame = CGRectMake((kBDScreenWidth - 25) / 2, kBDScreenHeight - 25 - 12 - 135 - kBDTopHeight, 25, 25);
}

- (LiuqsEmoticonKeyBoard *)emoticonKeyborad{
    if (!_emoticonKeyborad) {
        self.emoticonKeyborad = [LiuqsEmoticonKeyBoard showKeyBoardInView:self.view];
        _emoticonKeyborad.textView = self.textView;
        [self.view addSubview:_emoticonKeyborad];
    }
    return _emoticonKeyborad;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
